package client;

import java.util.LinkedList;
import java.util.Queue;

import utilities.ANSI;

/**
 * The Class ClientQueue.
 * 
 * @author Nils Berlijn
 * @author Henderikus Harms
 * @version 1.0
 * @since June 1, 2014
 *
 * @param <T> the generic type
 */
public class ClientQueue<T>
{
	/** The client queue. */
	private Queue<Runnable> clientQueue = new LinkedList<Runnable>();
    
    /** The capacity. */
    private int capacity;

    /**
     * Instantiates a new client queue.
     *
     * @param capacity the capacity
     */
    public ClientQueue(int capacity) 
    {
		System.out.println(ANSI.GREEN + "Client Queue is successfully launched." + ANSI.NORMAL);

        this.capacity = capacity;
        
		System.out.println(ANSI.YELLOW + "Client Queue is waiting for incoming data...\n" + ANSI.NORMAL);   
    }

    /**
     * Adds the.
     *
     * @param element the element
     * @throws InterruptedException the interrupted exception
     */
    public synchronized void add(Runnable element) throws InterruptedException 
    {
        while(clientQueue.size() == capacity) 
        {
            wait();
        }

        clientQueue.add(element);
        
        notify();
    }

    /**
     * Removes the.
     *
     * @return the runnable
     * @throws InterruptedException the interrupted exception
     */
    public synchronized Runnable remove() throws InterruptedException 
    {
        while(clientQueue.isEmpty()) 
        {
            wait();
        }
        
        Runnable item = clientQueue.remove();
        
        notify();
        
        return item;
    }
}
